package com.ssm.socket;


import com.qiniu.util.Hex;
import com.ssm.service.YlhService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class SocketModel implements ApplicationListener<ContextRefreshedEvent> {

    private ServerSocket serverSocket;


    @Autowired
    private YlhService ylhService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //通讯服务端绑定10005端口
        try {
            serverSocket = new ServerSocket(10005);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        //创建线程池,以便开启多线程通讯,避免端口阻塞
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        //保持一直循环,使程序一直监听
        while (true) {

            //监听端口
            Socket server;
            try {
                server = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
                log.error("发生监听io异常,详情: {}", e.getMessage());
                return;
            }
            //创建线程,线程处理通讯相关逻辑
            Runnable runnable = () -> {

                try {
                    log.info("等待远程连接，端口号为：" + serverSocket.getLocalPort() + "...");
                    log.info("远程主机地址：" + server.getRemoteSocketAddress());
                    //从监听socket中获取输入流
                    InputStream in = server.getInputStream();
                    //声明比特数组
                    byte[] bytes = new byte[1024];
                    int len;
                    //将输入流读取到比特数组
                    while ((len = in.read(bytes)) != -1) {
                        //剔除比特数组中多余的部分
                        byte[] newBytes = Arrays.copyOf(bytes, len);
                        //将比特流转为十六进制字符
                        String content = Hex.encodeHexString(newBytes);

                        log.info("接收到报文为: {}", content);
                        //传送报文
                        ylhService.sendContent(content);
                    }
                    //关流
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("发生io异常, 详情: {}", e.getMessage());
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    log.error("发生运行异常: {}", e.getMessage());
                }

            };
            //将线程加入线程池
            executorService.submit(runnable);

        }
    }

}
